<script setup lang="ts">
  import type { LocationQueryValue } from 'vue-router'
  import { articleAPI } from '~/apis/article'
  import type { ArticleItem } from '~/apis/article/model'

  const route = useRoute()
  const { data: page } = await useAsyncData('articlePage', () => queryContent('/article').findOne())

  if (!page.value) {
    throw createError({
      statusCode: 404,
      statusMessage: '未找到文章信息',
      fatal: true
    })
  }

  const state = reactive({
    pageNum: 1,
    pageSize: 9,
    count: 0,
    loading: false
  })

  const blogList = ref<ArticleItem[]>([])

  const getList = async () => {
    try {
      state.loading = true
      const { data: blog, pending } = await articleAPI.page({
        pageNum: state.pageNum,
        pageSize: state.pageSize,
        status: 'Published'
      })
      state.loading = false
      if (!blog.value) {
        throw createError({
          statusCode: 404,
          statusMessage: '未找到文章列表',
          fatal: true
        })
      }
      if (blog.value) {
        state.count = blog.value.count
        blogList.value = blog.value.list
      }
    } catch (error) {
      console.error(error)
    }
  }

  getList()

  const updatePageNum = (newPage: number) => {
    state.pageNum = newPage
    blogList.value = []
    getList()
  }

  const isEmpty = computed(() => {
    return !state.loading && state.count === 0
  })

  useSeoMeta({
    title: page.value.title,
    ogTitle: page.value.title,
    description: page.value.description,
    ogDescription: page.value.description
  })
</script>

<template>
  <UContainer v-if="page">
    <UPageHeader :title="page.title" :description="page.description" class="py-[50px]" />
    <UPageBody>
      <UBlogList :show-empty="isEmpty" :show-loading="state.loading">
        <UBlogPost
          v-for="(post, index) in blogList"
          :key="index"
          :to="{ path: `/article/detail/${post.id}` }"
          :title="post.title"
          :description="post.desc"
          :image="{
            src: post.coverUrl,
            loading: 'lazy'
          }"
          :date="new Date(post.createTime).toLocaleDateString()"
          :authors="[
            {
              name: post.authorName || 'L',
              avatar: {
                src: post.authorAvatar
              },
              to: 'https://gitee.com/lginsane'
            }
          ]"
          :badge="{
            label: post.typeName || ''
          }"
          orientation="vertical"
          :ui="{
            description: 'line-clamp-2'
          }"
        ></UBlogPost>
      </UBlogList>
      <UPagination
        v-if="state.count > state.pageSize"
        v-model="state.pageNum"
        :page-count="state.pageSize"
        :total="state.count"
        size="md"
        class="mt-8 flex justify-center"
        @update:model-value="updatePageNum"
      ></UPagination>
    </UPageBody>
  </UContainer>
</template>
